/**
 * 图片管理
 * @returns {[[Type]]} [[Description]]
 */
define([ '../../common/service', './picPreview', './countryCode', './comment'],
    function( http,  PicPreview, countryCode, Comment) {
        var Manage = function() {};
        Manage.prototype = $.extend(Manage.prototype, {
            init: function(query) {
                var self = this;

                //更改列表项
                if (window.sessionStorage.roleId == 6) {
                    var adimageList = $('table[list-manager="adimage-list"]');
                    var tmpHtml = '<th th-name="pic">' + I18N.getText('imageManage', 'image') + '</th>' + '<th th-name="createTime" sorting="down">' + I18N.getText('imageManage', 'createTime') + '</th>' + '<th th-name="totoalPageViews" sorting>' + I18N.getText('imageManage', 'totoalPageViews') + '</th>' + '<th th-name="numOfPageViews" sorting>' + I18N.getText('imageManage', 'numOfPageViews') + '</th>' + '<th th-name="peopleNumOfPageViews" sorting>' + I18N.getText('imageManage', 'peopleNumOfPageViews') + '</th>' + '<th th-name="spent" sorting>' + I18N.getText('imageManage', 'spent') + '</th>' + '<th th-name="clicks" sorting>' + I18N.getText('imageManage', 'clicks') + '</th>' + '<th th-name="ctr" sorting>CTR</th>' + '<th th-name="impressions" sorting>' + I18N.getText('imageManage', 'impressions') + '</th>' + '<th th-name="adCount" remind="' + I18N.getText('imageManage', 'adCountDesc') + '">' + I18N.getText('imageManage', 'adCount') + '</th>' + '<th th-name="reviewStatus" sorting>' + I18N.getText('imageManage', 'imageStatus') + '</th>' + '<th th-name="comments">' + I18N.getText('imageManage', 'comment') + '</th>';
                    $('thead tr', adimageList).html(tmpHtml);
                    $('#image-header-tools').hide();
                }

                if (window.sessionStorage.roleId == 3) {
                    $('table[list-manager="adimage-list"]').find('th[th-name="order"]').remove();
                }

                self.initUploadI18n();
                //初始化应用
                self.initListManager(function() {
                    self.createImageCache = {
                        count: 0,
                        images: {}
                    };
                    self.initAppSelect();
                    self.bingEvents();
                    self.initQueryImage();
                    self.initCreateAdModal();
                    self.initSelectImages();
                });
            },
            /**
             * [bingEvents 绑定事件]
             * @return {[type]} [description]
             */
            bingEvents: function() {
                var self = this;
                var adimagePage = $('#adimage-manager-page');
                //查询事件
                adimagePage.on('click', '#query-btn', $.proxy(self.initQueryImage, self));
                //细分数据
                adimagePage.on('change', '#image-breakdowns-select', $.proxy(self.breakdownsChange, self));
                //统计周期
                adimagePage.on('change', '#image-date-select', $.proxy(self.cycleChange, self));
                //仅新建广告
                adimagePage.on('click', '#image-isNew-checkbox', $.proxy(self.cycleChange, self));
                //打开图片、轮播图详情
                adimagePage.on('click', '.thumbnail-div', function() {
                    self.openImageModal($(this).data('mid'));
                });
                //上传
                adimagePage.on('click', '#btn-upload', $.proxy(self.uploadImageModal, self));

                //创建广告之复选框事件
                $('#adimage-row').on('click', 'input[type="checkbox"]', $.proxy(self.selectImage, self));

                //查看将要创建广告的图片
                adimagePage.on('click', '#create-image-show', $.proxy(self.showSelectImages, self));

                //创建广告事件
                adimagePage.on('click', '#btn-create', $.proxy(self.createByImages, self));
                //删除图片
                adimagePage.off('click', 'a[data-delete]').on('click', 'a[data-delete]', $.proxy(self.deleteImage, self));
                $('body').off('click', '.ui-dialog-wrap a[data-delete]').on('click', '.ui-dialog-wrap  a[data-delete]', $.proxy(self.deleteImage, self));


                $('#btn-next-step').on('click', $.proxy(self.nextStep, self));
                $('#open-adimage-modal').on('hide.bs.modal', $.proxy(self.closeImageModal, self));

                //图片范围
                var ownerSelect = $('#image-owner-select');
                ownerSelect.select2({
                    minimumResultsForSearch: Infinity
                });
                //美宣角色、外部美宣角色
                if (window.sessionStorage.roleId.indexOf(6) != -1) {
                    //  ownerSelect.select2('enable', false);
                    if (window.sessionStorage.roleId.indexOf(6) > -1) { //外部美宣不支持我的图片/其他图片
                        ownerSelect.parent().hide(); //隐藏筛选条件
                    }
                    //不支持查看细分
                    $('.detail-area').remove();
                    //不支持创建
                    $('.create-ad').remove();

                    //$('#image-breakdowns-select').remove();
                } else {
                    adimagePage.on('click', '.adimage-data', $.proxy(self.queryImageBreakdown, self));
                    //数据细分
                    $('#image-breakdowns-select').select2({
                        //                      dropdownCssClass: 'select2-custom-dropdown',
                        minimumResultsForSearch: Infinity
                    });
                    $('#image-breakdowns-select').select2("val", "gender");
                    $('.create-ad').show();
                }

                //临时处理内部美宣角色
                if (window.sessionStorage.roleId == 3) {
                    //不支持创建
                    $('.create-ad').remove();
                }

                //统计周期 select2
                var _dateSelect = $('#image-date-select');
                _dateSelect.select2({
                    minimumResultsForSearch: Infinity
                });


                //统计周期 搜索时输入框内增加提示语
                _dateSelect.on("keyup-change", function() {
                    console.log('obj');
                }).on("select2-close", function() {});
                //图片类型
                $('#image-type-select').select2({
                    minimumResultsForSearch: Infinity
                });
                $('#time-select').select2({
                    minimumResultsForSearch: Infinity
                });
                $('.superbox-list').click(function() {
                    $('#myModal').modal('show')
                });

                function getLocalTime(now) {
                    var year = now.getYear() + 1900;
                    var month = now.getMonth() + 1;
                    var date = now.getDate();
                    var hour = now.getHours();
                    var minute = now.getMinutes();
                    var second = now.getSeconds();
                    return year + "-" + month + "-" + date + "   " + hour + ":" + minute + ":" + second;
                }

                //绑定列表项中评价事件
                $("#adimage-list").off('click', '.comment-action');
                $("#adimage-list").on('click', '.comment-action', function() {
                    new Comment($(this).data('mid'));
                });

            },
            /**
             * [initAppSelect 应用列表初始化]
             * @return {[type]} [description]
             */
            initAppSelect: function() {
                var self = this;
                var par = {
                    typeId: 2 //1、主页; 2、应用
                };
                var param = {
                    param: JSON.stringify(par)
                }
                self.showLoading($('#adimage-manager-page'));
                //上传图片、查询图片
                http.do('/connectionobjects/searchConnectionObjectsByResourceManage', param, 'post').then(function(data) {
                    self.hideLoading($('#adimage-manager-page'));
                    if (data.flag == 'fail') {
                        kit.alert2(data.msg);
                        return;
                    }
                    data = _.sortBy(data.data, function(item) {
                        return item.name.toLowerCase();
                    });
                    var tmpHtml = '<option value="">' + I18N.getText('imageManage', 'allAppTags') + '</option>';
                    var tmpHtmlModal = '<option value="">' + I18N.getText('imageManage', 'plsChooseAppTags') + '</option>';
                    var tmpHtmlStats = '<option value="">' + I18N.getText('imageManage', 'plsUseAppTags') + '</option>';
                    var results = [{
                        id: -1,
                        text: I18N.getText('imageManage', 'allAppTags')
                    }];
                    for (var i = 0; i < data.length; i++) {
                        tmpHtml += '<option value="' + (data[i].name || '') + '">' + data[i].name + '</option>';
                        tmpHtmlModal += '<option value="' + (data[i].fbConnectionObjectId || '') + '">' + data[i].name + '</option>';
                        results.push({
                            id: data[i].id,
                            text: data[i].name,
                            configurations: data[i].productConfigurations
                        });
                        tmpHtmlStats += '<option value="' + (data[i].fbConnectionObjectId || '') + '">' + data[i].name + '</option>';
                    }

                    //查看图片
                    var appSelect = $('#app-select');
                    appSelect.html(tmpHtml);
                    appSelect.select2();

                    //上传图片
                    var appSelectModal = $('#app-select-modal');
                    appSelectModal.html(tmpHtmlModal);

                    //按应用过滤统计数据
                    var appSelectStats = $('#app-select-stats');
                    appSelectStats.html(tmpHtmlStats);
                    appSelectStats.select2();
                    self.hideLoading($('#adimage-manager-page'));
                }, function(msg, data, type, errorCode) {
                    self.hideLoading($('#adimage-manager-page'));
                    kit.alert2(I18N.getText('imageManage', 'getDatafail'));
                });
            },
            /*
             @初始化列表管理
             */
            initListManager: function(cb) {
                var _this = this;
                var settings = {
                    isDevelopMode: true,
                    supportSorting: true, //是否支持排序
                    supportAjaxPage: true, //是否支持配置列表ajxa分页[多列表两种状态都有时:统一配置项为true,禁用的列表项pageJson参数为空即可]
                    supportDrag: false,
                    supportConfig: false,
                    supportAdjust: true,
                    supportRemind: true,
                    sortUpText: '1',
                    sortDownText: '-1',
                    disableCache: false,
                    setTopVal:325,//调整吸顶的高度,需要减去这个高度
                    scrollDOM:$('.fmp-article'),//监听滚动条
                    sortingCallback: function(query, th) {
                        _this.params.sortList = [];
                        var defaultQuery = {
                                mongodbId: 1
                            },
                            sortQuery = {};

                        sortQuery[$(th).attr('th-name')] = $(th).attr('sorting');
                        _this.params.sortList.push(sortQuery);
                        _this.params.sortList.push(defaultQuery);
                        _this.params.cPage = 1; //触发排序 后 返回第一页
                        //  $.extend( _this.params, query);
                        _this.setPageCount();
                        _this.queryImage();
                    },
                    pageData: { //分页数据
                        'adimage-list': {
                            tPage: 10, //总页数
                            cPage: 1, //当前页
                            pSize: 10, //每页显示条数
                            tSize: 100 //总条数
                        }
                    },
                    pageCallback: function(query) {
                        $.extend(_this.params, query);
                        _this.imgagePage = query;
                        _this.setPageCount();
                        _this.queryImage();
                    }
                };
                //_this.listManager.init( cb );
                $('table[list-manager="adimage-list"]').listManager('init', settings, function(query) {
                    _this.imgagePage = query['adimage-list'];
                    cb();
                });
            },
            /**
             * [initQueryImage 初始化查询页面]
             * @return {[type]} [description]
             */
            initQueryImage: function(e) {
                var self = this;

                //根据图片类型不同 进行显示处理
                self.params = self.getQueryParams();


                var cycleArea = $('#cycle-area'); //统计周期所在区域
                if (e) { //当前点击按钮时候不重置
                } else {
                    $('#image-isNew-checkbox').get(0).checked = false;
                }
                self.params.days = $('#image-date-select').val();
                //清除排序标识【暂时处理方法，新版本的listManager.js将会提供方法】
                $('#adimage-row table thead th .sorting-action').removeClass('sorting-down sorting-up');
                //这段代码临时处理搜索后重显默认排序 后续listManager版本升级后，将会移除
                $('#adimage-row th[th-name="createTime"] .sorting-action').addClass('sorting-down');
                self.queryImage();
                $('[data-toggle="tooltip"]').tooltip();
            },
            /**
             * [queryImage 查询]
             * @param  {[type]} curPage [当前页]
             * @return {[type]}   [description]
             */
            queryImage: function(curPage) {
                var self = this;
                var loadingArea = $('#adimage-manager-page');
                self.showLoading(loadingArea);
                if (self.params.pSize == null) {
                    var listTable = $('table[list-manager="adimage-list"]').listManager('getListManager');
                    if (listTable && listTable.pageData && listTable.pageData.pSize) {
                        self.params.pSize = listTable.pageData.pSize;
                    } else {
                        self.params.pSize = 10;
                    }
                }
                if(curPage){
                    self.params.cPage=curPage;
                }
                http.do('/adresource/getAdimagesList', {
                    param: JSON.stringify(self.params)
                }, 'POST').then(function(data) {
                    if (data.flag == 'fail') {
                        self.hideLoading(loadingArea);
                        self.adjustHeight();
                        kit.alert2(data.msg);
                        return;
                    }
                    data = data.data;
                    self.params.tSize = data.summary ? (data.summary.totalCount ? data.summary.totalCount : 0) : 0;
                    self.setPageCount();
                    var _adimageRow = $('#adimage-row'),
                        _adimageList = $('#adimage-list'),
                        _carouselRow = $('#carousel-row'),
                        _carouselList = $('#carousel-list');

                    _carouselRow.hide();
                    if (window.sessionStorage.roleId == 6) {
                        //临时处理美宣角色
                        //如果美宣 列表与正常显示项不同
                        self.renderUidesignerImagesList(_adimageList, data.resources);
                    } else {
                        self.renderImagesList(_adimageList, data.resources, self.createImageCache.images);
                    }


                    if (self.params.isMy == 'true') {
                        $('[data-operation]').show();
                    } else {
                        $('[data-operation]').hide();
                    }
                    var _adimageTable = $('table[list-manager="adimage-list"]');
                    _adimageTable.listManager('resetTd', false);
                    _adimageRow.show();
                    $('.review-status-message').popover({
                        content: function() {
                            var content = $(this).data("popcontent");
                            return window.decodeURI(content);
                        }
                    })
                    self.hideLoading(loadingArea);
                    self.adjustHeight();
                }, function(msg, data, type, errorCode) {
                    self.hideLoading(loadingArea);
                    self.adjustHeight();
                    kit.alert2(I18N.getText('imageManage', 'getDatafail'));
                });
            },
            /**
             * { 细分数据查询 }
             *
             * @method     queryImageBreakdown
             * @param      {<type>}  e       { description }
             */
            queryImageBreakdown: function(e) {
                var self = this;
                if (e.target.localName == 'img') {
                    return;
                }
                if ($(e.target).parents(".checkbox").length > 0) {
                    return;
                }
                if ($(e.target).parents('tr').next().hasClass('img-stats')) {
                    $('.img-stats').remove();
                    return;
                }
                var mid = $(e.target).parents('tr').find('.thumbnail-div').data('mid');
                $('tr[data-img-stats-mid="' + mid + '"]').toggle('fast');
                var loadingArea = $('#listArea');
                var breakdowns = $('#image-breakdowns-select').val();
                self.showLoading(loadingArea);
                var params = {
                    'breakdowns': breakdowns,
                    'days': $('#image-date-select').val(),
                    'onlyNew': ($('#image-isNew-checkbox:checked')[0] ? 'true' : 'false')
                };
                $('.img-stats').remove();
                var _image = $(e.target).parents('tr').data("image-info").image;
                params.imageHash = _image.imageHash;
                var fbConnectionObjectId = $('#app-select-stats').val();
                if (fbConnectionObjectId && fbConnectionObjectId.length > 0) {
                    params.fbConnectionObjectIds = [parseInt(fbConnectionObjectId)];
                }


                http.do('/adresource/getAdgroupStatsByBreakdowns', {
                    param: JSON.stringify(params)
                }, 'POST').then(function(res) {
                    self.hideLoading(loadingArea);
                    if (res.flag == 'fail') {
                        kit.alert2(res.msg);
                        return;
                    }
                    var adImageStatsHtml = self.createAdImageStatsHtml(res.data, mid, breakdowns);

                    if ($(e.target).parents('tr').next().hasClass('adimage-stats')) {
                        $(e.target).parents('tr').next().html(adImageStatsHtml);
                    } else {
                        $(e.target).parents('tr').after(adImageStatsHtml);
                    }

                    var container = $('body,html');
                    var scrollTo = $(e.target).parents('tr');
                    container.animate({
                        scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - 35
                    });
                }, function(msg, data, type, errorCode) {
                    self.hideLoading(loadingArea);
                    kit.alert2(I18N.getText('imageManage', 'getDatafail'));
                });
            },
            /**
             * [queryImage 查询]
             * @param  {[type]} params [description]
             * @return {[type]}   [description]
             */
            queryImageBreakdowns: function(breakdowns) {
                var self = this;
                var loadingArea = $('#listArea');
                self.showLoading(loadingArea);
                var params = {
                    'breakdowns': breakdowns,
                    'days': $('#image-date-select').val(),
                    'onlyNew': ($('#image-isNew-checkbox:checked')[0] ? 'true' : 'false')
                };
                $('#adimage-list .adimage-data').off('click').on('click', function(e) {
                    var mid = $(this).find('.thumbnail-div').data('mid');
                    $('tr[data-img-stats-mid="' + mid + '"]').toggle('fast');
                });
                $('.img-stats').remove();
                $("#adimage-list .thumbnail-div[data-mid]").each(function(i, v) {
                    var that = this;
                    var mid = $(that).data("mid");
                    params.imageMd5 = mid.split('_')[0];

                    http.do('/adresource/getAdgroupStatsByBreakdowns', {
                        param: JSON.stringify(params)
                    }, 'POST').then(function(res) {
                        self.hideLoading(loadingArea);
                        if (res.flag == 'fail') {
                            kit.alert2(res.msg);
                            return;
                        }
                        var adImageStatsHtml = self.createAdImageStatsHtml(res.data, mid, breakdowns);

                        if ($(that).parents('tr').next().hasClass('adimage-stats')) {
                            $(that).parents('tr').next().html(adImageStatsHtml);
                        } else {
                            $(that).parents('tr').after(adImageStatsHtml);
                        }
                        self.hideLoading(loadingArea);

                    }, function(msg, data, type, errorCode) {
                        self.hideLoading(loadingArea);
                        kit.alert2(I18N.getText('imageManage', 'getDatafail'));
                    });
                });
            },
            /*
             @生成单个素材统计数据的HTML
             $.resources: 生成列表所需数据
             ^.tmpHtml: 生成列表HTML片段
             */
            createAdImageStatsHtml: function(resources, mid, breakdowns) {
                var self = this;
                var dataTrLen = $('table[list-manager="adimage-list"] thead[class!="set-top"] th:visible').length;
                if (!resources || resources.length === 0) {
                    return '<tr class="img-stats"  data-img-stats-mid="' + mid + '"><td colspan="' + dataTrLen + '" align="center">' + I18N.getText('imageManage', 'noData') + '</td></tr>';
                }
                resources = _.sortBy(resources, function(item) {
                    if (item.country) {
                        return item.country.toLowerCase();
                    }
                    return item;
                });
                var tmpHtml = '';
                var breakdownsAttr = breakdowns.split(',');
                $.each(resources, function(i, v) {
                    var bearkdownStr = '';
                    for (var i = 0; i < breakdownsAttr.length; i++) {
                        var breakdown = breakdownsAttr[i];
                        var key = v[breakdown];
                        if (breakdown == 'country') {
                            if (key && key.length > 0) {
                                var cty = countryCode[key];
                                if (cty) {
                                    cty.cn = cty.cn.trim() == '' ? cty.name : cty.cn;
                                    bearkdownStr += cty.code + ' (' + cty.cn + ')';
                                } else {
                                    bearkdownStr += key + ' ';
                                }
                            } else {
                                bearkdownStr += key + ' ';
                            }
                        } else if (breakdown == 'gender') {
                            if (key == 'female') {
                                bearkdownStr += I18N.getText('imageManage', 'famale') + ' ';
                            } else if (key == 'male') {
                                bearkdownStr += I18N.getText('imageManage', 'male') + ' ';
                            } else {
                                bearkdownStr += key + ' ';
                            }
                        }
                    }


                    tmpHtml += '<tr class="img-stats" data-img-stats-mid="' + mid + '">' + (window.sessionStorage.roleId == 3 ? '' : '<td class="c-white"></td>') + '<td name="adimage-icon" class="c-white">' + bearkdownStr + '</td>' + '<td  class="c-white"></td>' + '<td  class="c-white">' + centsToDollar(v.spent) + '</td>' + '<td  class="c-white">' + kit.percentage((v.impressions == 0 ? 0 : v.clicks / v.impressions)) + '</td>' + '<td  class="c-white">' + kit.percentage((v.clicks == 0 ? 0 : v.results / v.clicks)) + '</td>' + '<td  class="c-white">' + v.results + '</td>' + '<td  class="c-white">' + centsToDollar(v.results == 0 ? v.spent : v.spent / v.results) + '</td>' + '<td  class="c-white">' + v.uniqueImpressions + '</td>';
                    for (var i = 0; i < (dataTrLen - 9); i++) {
                        tmpHtml = tmpHtml + '<td  class="c-white"></td>';
                    }
                    tmpHtml = tmpHtml + '</tr>';


                });

                function centsToDollar(cents) {
                    return ("$" + (Number(cents) / 100).toFixed(2));
                }

                return tmpHtml;
            },
            /*
             @ 渲染素材列表
             $.resources: 生成列表所需数据
             */
            renderImagesList: function(_adimageList, resources, _selectImages) {
                var self = this;
                _adimageList.empty();
                if (!resources || resources.length === 0) {
                    return;
                }
                var tmpHtml;
                var widthStyle = self.params.resourceType == 'CAROUSEL' ? ' style="width:70px;" ' : '';
                var selectCount = 0;
                $.each(resources, function(i, v) {
                    tmpHtml = $('<tr  class="adimage-data" data-tr-mid="' + v.mongodbId + '">' + '<td> <div class="checkbox"><label><input type="checkbox" data-mid="' + v.mongodbId + '" class="checkbox create-checkbox" name="create"><span></span></label></div></td>' + '<td><div class="thumbnail-div" data-mid="' + v.mongodbId + '"  slider-type="images">' + '<img ' + widthStyle + ' src="' + v.litImgURL + '"></div></td>' + '<td>' + moment(new Date(v.createTime)).format('YYYY/MM/DD HH:mm:ss') + '</td>' + '<td>' + self.centsToDollar(v.spent ? v.spent : 0) + '</td>' + '<td>' + kit.percentage(v.ctr ? v.ctr : 0) + '</td>' + '<td>' + kit.percentage(v.cr ? v.cr : 0) + '</td>' + '<td>' + (v.results ? v.results : 0) + '</td>' + '<td>' + self.centsToDollar(v.cost ? v.cost : 0) + '</td>' + '<td>' + (v.uniqueImpressions ? v.uniqueImpressions : 0) + '</td>' + '<td>' + v.uploadUserName + '</td>' + '<td>' + v.adCount + '</td>' + '<td data-operation><a href="javascript:;" class="icon-btn" data-delete data-mid="' + v.mongodbId + '"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></a></td>' + '</tr>').data("image-info", {
                        mongodbId: v.mongodbId,
                        image: v
                    });
                    _adimageList.append(tmpHtml)
                    if (_selectImages[v.mongodbId]) {
                        //已选择的图片 选中复选框
                        tmpHtml.find("input[type='checkbox']").prop("checked", true);
                        tmpHtml.addClass("active");
                        selectCount++;
                    }
                });


                //如果当前页全部选中，则表头的复选框选中
                if (resources.length == selectCount) {
                    _adimageList.parents("table").find(".all").prop("checked", true);
                } else {
                    _adimageList.parents("table").find(".all").prop("checked", false);
                }


                if (window.sessionStorage.roleId == '3') {
                    $('#adimage-list .checkbox').each(function(index, el) {
                        $(this).parent().remove();
                    });
                }
            },
            /**
             * 根据美宣角色渲染图片列表
             * @param resources
             */
            renderUidesignerImagesList: function(_adimageList, resources) {
                    var self = this;
                    _adimageList.empty();
                    if (!resources || resources.length === 0) {
                        return;
                    }
                    var tmpHtml;
                    var widthStyle = self.params.resourceType == 'CAROUSEL' ? ' style="width:70px;" ' : '';
                    $.each(resources, function(i, v) {
                        var popcontent = v.adReviewFeedback ? v.adReviewFeedback.replace(/\"/g, "&quot;") : 'unkown!can not passed!';
                        popcontent = window.encodeURI(popcontent);
                        var popoverHtml = v.reviewStatus == 6 ? '<a href="javascript:void(0);" class="review-status-message"  data-toggle="popover" data-trigger="hover" data-placement="left" data-popcontent="' + popcontent + '"> <i class="fa fa-exclamation-triangle"></i></a>' : '';
                        var reviewStatusStr;
                        if (v.reviewStatus) {
                            switch (Number(v.reviewStatus)) {
                                case 0:
                                    reviewStatusStr = I18N.getText('imageReview', 'machinesToBeAudited');
                                    break;
                                case 1:
                                    reviewStatusStr = I18N.getText('imageReview', 'byManualReview');
                                    break;
                                case 2:
                                    reviewStatusStr = I18N.getText('imageReview', 'notByManualReview');
                                    break;
                                case 4:
                                    reviewStatusStr = I18N.getText('imageReview', 'machineAudit');
                                    break;
                                case 5:
                                    reviewStatusStr = I18N.getText('imageReview', 'pendingManualReview');
                                    break;
                                case 6:
                                    reviewStatusStr = I18N.getText('imageReview', 'theMachineDoesNotPassTheAudit');
                                    break;
                                default:
                                    reviewStatusStr = "";
                            }
                        } else {
                            reviewStatusStr = "";
                        }
                        var commentHtml = '<span data-mid="' + v.id + '" class="comment-action" style="cursor:pointer;" data-comments ="' + (v.comments ? v.comments.replace(/\"/g, "&quot;") : "") + '"><i class="fa fa-comment-o icon-btn"></i></span>';
                        tmpHtml = '<tr class="adimage-data" data-tr-mid="' + v.mongodbId + '">' + '<td><div class="thumbnail-div" data-mid="' + v.mongodbId + '"  slider-type="images">' + '<img' + widthStyle + ' src="' + v.litImgURL + '"></div></td>' + '<td>' + moment(v.createTime).format('YYYY/MM/DD HH:mm:ss') + '</td>' + '<td>' + (v.totoalPageViews ? v.totoalPageViews : '') + '</td>' + '<td>' + (v.numOfPageViews ? v.numOfPageViews : '') + '</td>' + '<td>' + (v.peopleNumOfPageViews ? v.peopleNumOfPageViews : '') + '</td>' + '<td>' + self.centsToDollar(v.spent ? v.spent : 0) + '</td>' + '<td>' + (v.clicks ? v.clicks : 0) + '</td>' + '<td>' + kit.percentage(v.ctr ? v.ctr : 0) + '</td>' + '<td>' + (v.impressions ? v.impressions : 0) + '</td>' + '<td>' + (v.adCount ? v.adCount : 0) + '</td>' + '<td>' + reviewStatusStr + popoverHtml + '</td>' + '<td>' + (v.comments ? commentHtml : "--") + '</td>' + '</tr>';
                        _adimageList.append(tmpHtml);
                    });

                }
                /*
                 @统计周期变更
                 */
                ,
            breakdownsChange: function() {
                var _this = this;
                var dateSelect = $('#image-breakdowns-select');
                var breakdowns = $(dateSelect).val();
                $('.img-stats').remove();
                if (breakdowns == '') {
                    return;
                }
                //_this.queryImageBreakdowns(breakdowns);
            },
            /*
             @统计周期变更
             */
            cycleChange: function() {
                var _this = this;
                var dateSelect = $('#image-date-select'),
                    isNewCheckbox = $('#image-isNew-checkbox');
                if (!_this.params) {
                    _this.params = {};
                }
                _this.params.days = $('#image-date-select').val();
                _this.params.onlyNew = isNewCheckbox.get(0).checked ? 'true' : 'false';
                //  _this.params.sortList = [];
                _this.params.cPage = 1; //触发排序 后 页三返回第一页
                _this.resetBreakdownSelect();
                _this.setPageCount();
                _this.queryImage();
            },
            /*
             @配置分页数据
             */
            setPageCount: function() {
                var _this = this;
                if (!_this.params) {
                    _this.params = {}
                }
                if (!_this.imgagePage) {
                    _this.imgagePage = {}
                }
                var tSize = _this.params.tSize;
                //当前搜索为图片
                var paginator = {
                    tSize: tSize,
                    pSize: _this.params.pSize,
                    tPage: Math.ceil(tSize / _this.params.pSize),
                    cPage: _this.params.cPage || 1
                };
                $('[list-manager="adimage-list"]').listManager('resetPageData', paginator);

            },
            /**
             * [getQueryParams 得到查询参数]
             * @return {[type]} [description]
             */
            getQueryParams: function() {
                var self = this;
                if (!self.imgagePage) {
                    self.imgagePage = {}
                }
                var params = {
                    cPage: 1,
                    pSize: self.imgagePage.pSize
                };

                params.resourceType = $('#image-type-select').val(); //图片类型
                params.isMy = $('#image-owner-select').val(); //是否自己的图片
                params.onlyNew = ($('#image-isNew-checkbox:checked')[0] ? 'true' : 'false');
                var $sort = $("#sort-area li.active");
                var appName = $('#app-select').val();
                if (appName && appName.length > 0) {
                    params.appNames = [appName];
                }
                var fbConnectionObjectId = $('#app-select-stats').val();
                if (fbConnectionObjectId && fbConnectionObjectId.length > 0) {
                    params.fbConnectionObjectIds = [parseInt(fbConnectionObjectId)];
                }


                //依据图片类型 设置不同的初始排序
                params.sortList = [{
                    createTime: -1,
                }, {
                    mongodbId: 1
                }];


                if (window.imageBathId) {
                    //删除掉查询条件
                    delete params.resourceType;
                    delete params.isMy;
                    delete params.appNames;
                    //       delete params.tags;
                    params.imageBathId = window.imageBathId;
                }
                params.days = $('#image-date-select').val();

                self.resetBreakdownSelect();
                return params;
            },
            /**
             * [openImageModal 打开图片信息]
             * $._mid_:图片ID
             * @return {[type]}   [description]
             */
            openImageModal: function(_mid_) {
                var self = this;
                var picPreview = new PicPreview(_mid_, self.params);

            },
            /**
             * [closeImageModal 关闭图片信息]
             * @param  {[type]} e [description]
             * @return {[type]}   [description]
             */
            closeImageModal: function(e) {
                var self = this;
                $('.popover.fade.bottom.in').remove();
            },
            /**
             * [uploadImageModal 上传图片]
             * @param  {[type]} e [description]
             * @return {[type]}   [description]
             */
            url: cors_config.adresource_uploadImg,

            uploadImageModal: function(e) {
                var self = this;
                self.uploadMids = []; //初始化上传存储mongodid
                $('#upload-adimage-modal').modal({
                    backdrop: 'static',
                    keyboard: false
                });
                $('#upload-adimage-modal').modal('show');
                $('#upload-adimage-modal').addClass('no-picture-upload'); //添加背景 hover
                $('#modal-btn-preview').addClass('hide');
                $('#upload-area').html('<input id="input-dim-2" type="file" name="files"  multiple=true class="file-loading" accept="image/*">');
                $('#app-select-modal').val('');
                $('#app-select-modal').select2();
                $('#upload-adimage-modal').removeAttr('tabindex');
                $('#modal-btn-upload').removeClass('hide');
                $('.file-preview-frame.add-image-btn').removeClass('hide');
                $('#btn-next-step').addClass('hide');
                $('#cancel-btn').addClass('hide');
                $('#upload-adimage-modal .modal-alert').text('');
                // $('#modal-btn-upload').removeClass('hide');
                // $('#btn-next-step').addClass('hide');
                var $inputUpload = $("#input-dim-2");
                $inputUpload.fileinput('destroy');
                $inputUpload.fileinput({
                    language: (localStorage.language == 'en-us' ? 'en-us' : 'zh'),
                    showCaption: false,
                    showRemove: false,
                    showUpload: false,
                    showCancel: false,
                    uploadAsync: false,
                    isThirdPic: window.sessionStorage.roleId == 6 ? true : false,
                    uploadUrl: 'http://walle.clientgear.com/adresource/uploadImg',
                    allowedFileExtensions: ["jpg", "png", "gif", "jpeg"],
                    maxFileCount: 50, //文件个数
                    maxFileSize: 7 * 1024 * 1024, //支持的最大文件大小
                    browseClass: 'btn btn-default',
                    uploadClass: 'btn btn-primary',
                    showPreview: true,
                    msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
                    previewSettings: {
                        image: {
                            width: "150px",
                            height: "100px"
                        },
                    },
                    fileActionSettings: {
                        uploadClass: 'hide',
                        removeTitle: I18N.getText('imageManage','removeTitle'),
                        indicatorNewTitle: I18N.getText('imageManage','indicatorNewTitle'),
                        indicatorSuccessTitle: I18N.getText('imageManage','indicatorSuccessTitle'),
                        indicatorErrorTitle: I18N.getText('imageManage','indicatorErrorTitle'),
                        indicatorLoadingTitle: I18N.getText('imageManage','indicatorLoadingTitle'),
                    },
                    layoutTemplates: {
                        actionDelete: '<button type="button" class="kv-file-remove close" title="{removeTitle}"{dataUrl}{dataKey}><span aria-hidden="true">×</span></button>',
                        footer: '<div class="file-thumbnail-footer">\n' +
                            '    <div class="file-caption-name" style="width:{width}">{caption}</div>\n' +
                            '    {actions}\n' +
                            '</div>'
                    },
                    uploadExtraData: function() {
                        var fileNames = [];
                        $('.file-preview-thumbnails img').each(function() {
                            var title = $(this).attr('title');
                            fileNames.push(title);
                        });
                        var appId = $('#app-select-modal').val();
                        var appName = $('#app-select-modal option:checked').text().trim();
                        if (appId == '') {
                            appName = '';
                        }
                        return {
                            appId: appId,
                            appName: appName,
                            fileNames: fileNames
                        };
                    },
                    ajaxSettings: {
                        xhrFields: {
                            withCredentials: true
                        }
                    }
                }).on('filebatchuploadcomplete', function(event, files, extra) {
                    var allNum = $('.file-preview .file-preview-frame.file-preview-success').length;
                    var successNum = $('.file-preview .file-preview-frame.file-preview-success .file-icon-large.text-success').length;
                    if (successNum > 0 && allNum == successNum) {
                        // $('#btn-next-step').trigger('click');
                    }
                    var process = $('.progress-bar.progress-bar-success').html().trim();
                    if (process == "100%") {}
                    $('.kv-upload-progress').hide();
                    $('#modal-btn-upload').addClass('hide');
                    $('.file-preview-frame.add-image-btn').addClass('hide');
                    $('#btn-next-step').removeClass('hide');
                    $('#cancel-btn').removeClass('hide');
                }).on('filebatchuploadsuccess', function(event, data, previewId, index) {
                    if (data.response.flag === 'success') {
                        self.showUploadMsg(null, data.response.data);
                    } else if (data.response.flag === 'fail') {
                        self.showUploadMsg(data.response.msg);
                    } else {}


                    $('#cancel-btn').off('click').on('click', function() {
                        setTimeout(function() {
                            $('#query-btn').trigger('click')
                        }, 200)
                    });



                }).on('filepreajax', function(event, previewId, index) {
                    var errorFilesLen = $('.file-preview-thumbnails .file-preview-frame .file-upload-indicator .text-danger').length;
                    if (errorFilesLen > 0) {
                        $inputUpload.fileinput('cancel');
                        setTimeout(function() {
                            $('.fileinput-cancel-button').trigger('click');
                        }, 200);
                        return {
                            message: I18N.getText('imageManage', 'PlsRemoveErrorFile')
                        };
                    }
                }).on('filepreremove', function(event, previewId) {
                    console.info('filepreremove')
                    $('#' + previewId).tooltip('destroy');
                    $('.file-drop-zone .tooltip').remove();
                }).on('fileloaded', function(event, file, previewId, index, reader) {

                    if (file.type.indexOf('image/') == 0) {
                        var reader = new FileReader();
                        reader.onload = (function(f) {
                            return function(e) {
                                $('#' + previewId).data('base64', e.target.result)
                            };
                        })(file);
                        reader.readAsDataURL(file);
                    } else {
                        $('#' + data.id).remove();
                    }
                    $('#upload-adimage-modal').removeClass('no-picture-upload'); //文件加载后移除背景 hover
                    $("#upload-adimage-modal .modal-body").unbind('click');
                    $('#modal-btn-preview').removeClass('hide');
                }).on('filereset', function(event, previewId) {
                    $('#upload-adimage-modal .modal-alert').html('');
                    $('#upload-adimage-modal').addClass('no-picture-upload'); //input reset 后添加背景 hover
                    $('#modal-btn-preview').addClass('hide');
                }).on('fileuploaderror', function(event, data, previewId, index) {
                    if (data.ind) {
                        return;
                    }
                    if (data.files) {
                        if (data.files.length <= 50) {
                            if (data.files[data.index].type.startsWith('image/')) {

                            } else {
                                $('#' + data.id).remove();
                            }

                        } else {
                            self.errorMsg(I18N.getText('imageManage', 'PlsReChooseFile'));
                            $inputUpload.fileinput('reset');
                        }
                    }
                    setTimeout(function() {
                        $('#upload-area .kv-fileinput-error.file-error-message').hide()
                    }, 440);
                }).on('fileuploaderror', function(event, previewId) {
                    console.log('fileuploaderror');
                    var $file = $('#' + previewId.id);
                    setTimeout(function() {
                        $file.tooltip('destroy');
                        setTimeout(function() {
                            $file.tooltip({
                                placement: 'top',
                                container: '#upload-adimage-modal'
                            });
                            var tipId = $file.attr('aria-describedby');
                            $('#' + tipId).css('z-index', '9999');
                        }, 50)
                    }, 500);
                }).on('filecleared', function(event, previewId) {}).on('filedeleted', function(event, previewId) {}).on('filesuccessremove', function(event, previewId) {
                    $('.tooltip.fade.top.in').remove()
                }).on('fileerror', function(event, previewId) {
                    $('#upload-area .kv-fileinput-error.file-error-message').hide()
                }).on('fileimageloaded', function(event, previewId) {
                    $('#upload-area .add-image-btn').remove();
                    $('#upload-area .file-preview-thumbnails').append('<div class="file-preview-frame add-image-btn"> <i class="glyphicon glyphicon-plus"></i></div>');
                    setTimeout(function() {
                        $("#upload-area .add-image-btn .glyphicon-plus").unbind('click').on('click', function() {
                            var fileInput = document.getElementById("input-dim-2");
                            fileInput.click(); //加一个触发事件
                        });
                        self.showMsgs(I18N.getText('imageManage', 'selectedDesc') + '<span class="image-count">' + ($('#upload-area .file-preview-frame .file-thumbnail-footer').length) + '</span>' + I18N.getText('imageManage', 'selectedNums'))
                        $('#upload-area .kv-fileinput-error.file-error-message').hide()
                        $('.file-preview-thumbnails img').each(function() {
                            if (($(this)[0].naturalWidth > 0) && ($(this)[0].naturalWidth == $(this)[0].naturalHeight)) {
                                $(this).width(100)
                            }
                        });

                        // 图片加载后的错误提醒
                        $('.file-preview-thumbnails .file-preview-frame.file-preview-error').each(function(i, v) {
                            var msg = '<div class="file-preview-error-msg"><i class="glyphicon glyphicon-info-sign icon-message"></i><p>素材尺寸不符合规范</p></div>';
                            if (!$(this).find('.file-preview-error-msg')[0]) {
                                $(this).prepend(msg);
                            }
                        });
                    }, 200);
                }).on('filereset', function(event, previewId) {
                    setTimeout(function() {
                        $("#upload-adimage-modal .modal-body").unbind('click').on('click', function() {
                            var fileInput = document.getElementById("input-dim-2");
                            fileInput.click(); //加一个触发事件
                        });
                    }, 200);
                }).on('fileremoved', function(event, previewId) {
                    if ($('#upload-area .file-preview-frame .file-thumbnail-footer').length == 0) {
                        $('#upload-area .add-image-btn').remove();
                        $inputUpload.fileinput('reset');
                        $('#upload-adimage-modal .modal-alert').text('');
                    } else {
                        self.showMsgs(I18N.getText('imageManage', 'selectedDesc') + '<span class="image-count">' + ($('#upload-area .file-preview-frame .file-thumbnail-footer').length) + '</span>' + I18N.getText('imageManage', 'selectedNums'))
                    }


                })

                $('#upload-adimage-modal .file-preview-frame.btn.disabled .kv-file-remove .text-danger').off('click')
                $('#upload-adimage-modal').on('click', '.file-preview-frame.btn.disabled .kv-file-remove .text-danger', function(e) {
                    var $el = $(e.target).parents('.file-preview-frame.btn.disabled');
                    $('.file-drop-zone .tooltip').remove();
                    $el.remove();
                    var errorFilesLen = $('.file-preview-thumbnails .file-preview-frame .file-upload-indicator .text-danger').length;
                    if (errorFilesLen == 0) {
                        $('.form-control.file-caption.kv-fileinput-caption')
                    }
                })
                $('#modal-btn-upload').off('click')
                $('#modal-btn-upload').on('click', function(e) {
                    var errorFilesLen = $('.file-preview-thumbnails .file-preview-frame.file-preview-error').length;
                    if (errorFilesLen > 0) {
                        self.errorMsg(I18N.getText('imageManage', 'PlsRemoveErrorFile'));
                        return;
                    }

                    var uploadFileLen = $('.file-preview-thumbnails .file-preview-frame .file-thumbnail-footer').length;
                    if (uploadFileLen == 0) {
                        self.errorMsg(I18N.getText('imageManage', 'PlsChooseUploadFile'));
                        return;
                    }

                    var appId = $('#app-select-modal').val();
                    if (appId == '') {
                        $('#app-select-modal').testRemind(I18N.getText('imageManage', 'plsChooseAppTags'));
                        $('#app-select-modal').next().testRemind(I18N.getText('imageManage', 'plsChooseAppTags'));
                        return;
                    }
                    $inputUpload.fileinput('upload');
                });

                $("#upload-adimage-modal .modal-body").unbind('click').on('click', function() {
                    var fileInput = document.getElementById("input-dim-2");
                    fileInput.click(); //加一个触发事件
                });
                /**
                 * 点击预览
                 * @param  {[type]} "#modal-btn-preview" [description]
                 * @return {[type]}                      [description]
                 */
                $("#modal-btn-preview").unbind('click').on('click', function() {
                    var previewImgs = $('.file-preview-thumbnails .file-preview-frame').not('.file-preview-error').not('.add-image-btn');
                    if (previewImgs.length == 0) {
                        self.showMsgs(I18N.getText('imageManage', 'noPreviewImage'), 'info');
                        return false;
                    }
                    var previewImgSrcs = [];
                    previewImgs.each(function(i, v) {
                        var base64 = $(this).data('base64');
                        if (base64.length > 0) {
                            previewImgSrcs.push(base64);
                        }
                    });
                    window.localStorage.setItem('previewImgSrcs', JSON.stringify(previewImgSrcs));
                    window.open('./preview.html');
                });
            },


            /**
             * [showUploadMsg 显示错误信息]
             * @param  {[type]} errorMsg          [错误信息]
             * @param  {[type]} fileErrors   [文件错误信息,有多个]
             * @return {[type]}              [description]
             */
            showUploadMsg: function(errorMsg, fileErrors) {
                    var self = this;
                    setTimeout(function() {
                        if ((errorMsg && errorMsg.length > 0) || (fileErrors && fileErrors.length > 0)) {
                            if (errorMsg && errorMsg.length > 0) {
                                self.errorMsg((errorMsg) || I18N.getText('imageManage', 'plsChooseUploadFile'));
                                $("#input-dim-2").fileinput('refresh');
                                return;
                            } else {
                                var msg = $(".kv-fileinput-error.file-error-message");
                                var msgHtml = '<span class="close kv-error-close">×</span><ul>';
                                var errorNum = 0;
                                var totalNum = 0;
                                var filePreview = $('.file-preview-thumbnails .file-preview-frame:not(.add-image-btn)');
                                if (fileErrors && fileErrors.length > 0) {
                                    totalNum = fileErrors.length;
                                    _.each(fileErrors, function(file, idx) {
                                        if (file.mongodbId && file.mongodbId.length > 0) {
                                            self.uploadMids.push(file.mongodbId);
                                        }
                                        if (file && file.mongodbId) {
                                            $(filePreview[idx]).data('mId', file.mongodbId);
                                        } else {
                                            $(filePreview[idx]).data('mId', 0);
                                        }
                                        if ((window.sessionStorage.roleId == 6) && file && file.exist) { //图片已经存在
                                            file.msg = I18N.getText('imageManage', 'imageExists')
                                        }
                                        if (file && file.msg && file.msg.length > 0) {
                                            $(filePreview[idx]).addClass('upload-error-msg').addClass('file-preview-error');
                                            $(filePreview[idx]).attr('title', file.msg);
                                            $(filePreview[idx]).tooltip('destroy');
                                            $(filePreview[idx]).tooltip({
                                                placement: 'top',
                                                container: 'body'
                                            });
                                            //msgHtml = msgHtml + '<li>'+file.fileName+' ' + file.msg + '</li>'
                                            errorNum++;
                                        }
                                    });
                                }
                                msgHtml = msgHtml + '</ul>'
                                    // $('#upload-adimage-modal .file-preview-frame .kv-file-remove.close').off('click').on('click',function(){
                                    //     $('.tooltip.fade.top.in').remove()
                                    // });
                                self.showMsgs('');
                                if (errorNum > 0) {
                                    //msg.html(msgHtml).show();
                                    //msg.find('.kv-error-close').off('click').on('click', function () {
                                    //    msg.fadeOut('slow');
                                    //});
                                    self.errorMsg(I18N.getText('imageManage', 'success') + '<span class="image-count">' + (totalNum - errorNum) + '</span>' + I18N.getText('imageManage', 'item') + '  (' + '<span class="image-count">' + errorNum + '</span>' + I18N.getText('imageManage', 'fail') + ')', 'error')
                                } else {
                                    self.okMsg(I18N.getText('imageManage', 'success') + '<span class="image-count">' + (totalNum - errorNum) + '</span>' + I18N.getText('imageManage', 'item'))
                                }

                            }
                        }
                    }, 300);
                }
                /**
                 * [nextStep 下一步编辑图片信息]
                 * @param  {[type]} e [description]
                 * @return {[type]}   [description]
                 */
                ,
            nextStep: function(e) {
                var self = this;
                var filesLen = $('.file-preview-thumbnails .file-preview-frame .file-upload-indicator').length;
                var successFilesLen = $('.file-preview-thumbnails .file-preview-frame:not(.upload-error-msg) .file-upload-indicator .text-success').length;
                if (filesLen === 0) {
                    self.showMsgs(I18N.getText('imageManage', 'PlsChooseUploadFile'), 'info');
                    return;
                }
                if (filesLen !== successFilesLen) {
                    self.showMsgs(I18N.getText('imageManage', 'PlsRemoveErrorFile'), 'info');
                    return;
                }
                var appId = $('#app-select-modal').val();
                var appName = $('#app-select-modal option:checked').text().trim();
                var uploadMids = [];
                $('.file-preview-thumbnails .file-preview-frame:not(.add-image-btn):not(.upload-error-msg)').each(function() {
                    uploadMids.push($(this).data("mId"));
                });
                if (uploadMids.length == 0) {
                    self.showMsgs(I18N.getText('imageManage', 'PlsChooseUploadFile'), 'info');
                    return;
                }
                var mongodbIds = uploadMids.join('|');
                if (appId == '') {
                    appName = '';
                    $('#app-select-modal').testRemind(I18N.getText('imageManage', 'plsChooseAppTags'));
                    $('#app-select-modal').next().testRemind(I18N.getText('imageManage', 'plsChooseAppTags'));
                    return;
                }
                var params = {
                    mongodbIds: mongodbIds,
                    fbConnectionObjectId: appId,
                    appName: appName
                }
                $('#upload-adimage-modal').modal('hide');
                $('.modal-backdrop').remove();
                $('body').removeClass('modal-open');
                window.localStorage.setItem('imageEditData', JSON.stringify(params));
                window.location.hash = '#!imageEdit';
            },
            /**
             * [imageTypeChange 图片类型切换]
             * @param  {[type]} e [description]
             * @return {[type]}   [description]
             */
            /*
             imageTypeChange: function(e) {
             var self = this;
             $('.sort-li').toggleClass('hide');
             },
             */
            showLoading: function($dom) {
                var self = this;
                var loadingArea = $dom ? $dom : $('#widget-grid');
                kit.loading.show(loadingArea);
            },
            hideLoading: function($dom) {
                var self = this;
                var loadingArea = $dom ? $dom : $('#widget-grid');
                kit.loading.hide(loadingArea);
            },
            dispose: function() {

            },
            deleteImage: function(e) {
                var self = this;
                e.stopPropagation();

                var mid = $(e.currentTarget).closest('a').data('mid');


                $('#delete-image-modal').modal('show');
                $('#delete-image-modal .btn-primary').off('click').on('click', function(e) {
                    var params = {
                        mongodbIds: mid
                    }
                    self.showLoading($('#listArea'));

                    http.do('/adresource/deleteAdImages', {
                        param: JSON.stringify(params)
                    }, 'POST').then(function(res) {
                        self.hideLoading($('#listArea'));
                        if (res.flag == 'fail') {
                            kit.alert2(res.msg);
                            return;
                        }
                        $('#adimage-list').find('input[data-mid="' + mid + '"]:checked').trigger('click');
                        setTimeout(function() {
                            $('#adimage-list tr[data-tr-mid="' + mid + '"]').remove();
                            $('#adimage-list tr[data-img-stats-mid="' + mid + '"]').remove();
                            var curPage = $('.page-toolbar .pagination li.active').text()*1;//当前页
                            if($('#adimage-list tr[data-tr-mid]').length==0){
                                curPage=curPage>1?curPage-1:curPage;
                            }
                            self.queryImage(curPage);
                            self.hideLoading($('#listArea'));
                            $('#delete-image-modal').modal('hide');
                            $('.ui-dialog-wrap .ui-dialog-close').trigger('click');

                        },50);

                    }, function(msg, data, type, errorCode) {
                        self.hideLoading($('#listArea'));
                        $('.ui-dialog-wrap .ui-dialog-close').trigger('click');
                        $('#delete-image-modal').modal('hide');
                        kit.alert2(I18N.getText('imageManage', 'getDatafail'));
                    });

                });
            },
            /**
             * { 重置细分数据slect2 }
             *
             * @method     resetBreakdownSelect
             */
            resetBreakdownSelect: function() {

            },
            /*
             @信息提示
             $.msg:文本
             $.type: 类型
             $.cb: 回调
             */
            showMsgs: function(msg, type, cb) {
                var color = type == 'error' ? '#f00' : '#333';
                var uploadAdimageModal = $('#upload-adimage-modal'),
                    modalAlert = $('.modal-alert', uploadAdimageModal);
                modalAlert.html(msg).css('color', color);
                //modalAlert.slideDown(500);
                //window.setTimeout(function () {
                //    modalAlert.slideUp();
                //    typeof(cb) == 'function' ? cb() : '';
                //}, 1500);
            },
            /**
             * 创建广告选择图片
             */
            selectImage: function(e) {
                e.stopImmediatePropagation();
                var self = this;
                if ($(e.target).hasClass("all")) {
                    // 表头全选复选框
                    var _listArea = $("#listArea");
                    var _createCheckboxs = _listArea.find(".create-checkbox")
                    if ($(e.target).get(0).checked) {
                        //全选
                        //将没有选中的图片找出
                        var _image;
                        var _tr;
                        _createCheckboxs.each(function(index, _createCheckbox) {
                            if (!$(_createCheckbox).is(':checked')) {
                                $(_createCheckbox).prop("checked", true);
                                _tr = $(_createCheckbox).parents("tr");
                                _image = _tr.data("image-info");
                                _tr.addClass("active");
                                self.createImageCache.images[_image.mongodbId] = _image.image
                                self.createImageCache.count += 1;
                            }

                        });
                    } else {
                        //全不选
                        //全选
                        //将没有选中的图片找出
                        var _image;
                        var _tr;
                        _createCheckboxs.each(function(index, _createCheckbox) {
                            if ($(_createCheckbox).is(':checked')) {
                                $(_createCheckbox).prop("checked", false);
                                _tr = $(_createCheckbox).parents("tr");
                                _image = _tr.data("image-info");
                                _tr.removeClass("active");
                                delete self.createImageCache.images[_image.mongodbId];
                                self.createImageCache.count -= 1;
                            }

                        });
                    }
                } else {
                    // 列表选择复选框
                    var _createCheckbox = e.target;
                    var _image;
                    var _tr;
                    if ($(e.target).get(0).checked) {
                        $(_createCheckbox).prop("checked", true);
                        _tr = $(_createCheckbox).parents("tr");
                        _image = _tr.data("image-info");
                        _tr.addClass("active");
                        self.createImageCache.images[_image.mongodbId] = _image.image
                        self.createImageCache.count += 1;
                    } else {
                        $(_createCheckbox).prop("checked", false);
                        _tr = $(_createCheckbox).parents("tr");
                        _image = _tr.data("image-info");
                        _tr.removeClass("active");
                        delete self.createImageCache.images[_image.mongodbId];
                        self.createImageCache.count -= 1;
                    }

                    var _listArea = $("#listArea");
                    if (_listArea.find("tbody").find("input:checked").length == _listArea.find("tbody").find("tr").length) {
                        _listArea.find(".all").prop("checked", true);
                    } else {
                        _listArea.find(".all").prop("checked", false);
                    }
                }

                var count = self.createImageCache.count;
                $(".image-count").text(count);
                if (0 < count) {
                    //有选择的图片才可以创建广告
                    $("#btn-create").removeClass("disabled");
                    $("#create-image-show").removeClass("disabled");
                } else {
                    $("#btn-create").addClass("disabled");
                    $("#create-image-show").addClass("disabled");
                }
            },
            /**
             * [adjustHeight 调整高度]
             * @return {[type]} [description]
             */
            adjustHeight: function() {
                /*
                var container = $('body,html');
                    container.animate({
                        scrollTop: 100
                    });
                  */
                $(window).trigger('resize');
                /*
                 var height= $('#listArea').height();
                 $('body').css('min-height',height+'px');
                 */
            },
            initSelectImages: function() {
                var self = this;
                //列表管理
                var settings = {
                    supportSorting: true //是否支持排序
                        ,
                    supportDrag: false,
                    supportConfig: false,
                    supportAdjust: true,
                    supportRemind: true,
                    sortUpText: '1',
                    sortDownText: '-1',
                    scrollDOM: '.show-image-container',
                    //配置排序所需要的搜索事件源
                    sortingCallback: function(params) {
                        var resources = [];
                        $.each(self.createImageCache.images, function(_mongodbId, _image) {
                            _image.createTime = moment(new Date(_image.createTime)).valueOf();
                            resources.push(_image);
                        });
                        var p = {};
                        for (prop in params) {
                            if (params[prop].length > 0) {
                                p.key = prop;
                                p.val = params[prop];
                                break;
                            }
                        }

                        //对已选图片进行排序
                        var results = resources.sort(function(a, b) {
                            return (Number(a[p.key]) - Number(b[p.key])) * Number(p.val);
                        });

                        //获取当前查看列表中已选的图片
                        var _createAdimageList = $('table[list-manager="create-adimage-list"]');
                        var _selectImageTrs = _createAdimageList.find("tbody").find("input:checked");
                        var _image;
                        var _selectImages = {};
                        $.each(_selectImageTrs, function(i, _selectCheckbox) {
                            _image = $(_selectCheckbox).parents("tr").data("image-info");
                            _selectImages[_image.mongodbId] = _image;
                        })

                        self.renderImagesList($('#select-adimage-list'), results, _selectImages);
                        $('#select-adimage-list td[data-operation]').remove();
                    }
                };
                var _createAdimageList = $('table[list-manager="create-adimage-list"]');
                _createAdimageList.listManager('init', settings);

                $("#show-image-btn").off("click").on("click", function() {
                    //获取未选中的图片，修改缓存，并将列表中复选框置为未选
                    var unSelecteds = $('#select-adimage-list').find('input[type="checkbox"]').not("input:checked");
                    if (0 < unSelecteds.length) {
                        var _image;
                        var _adimageList = $("#adimage-list");
                        var _adimageListTr;
                        var _adimageListC;
                        $.each(unSelecteds, function(index, _createCheckbox) {
                            _image = $(_createCheckbox).parents("tr").data("image-info");

                            delete self.createImageCache.images[_image.mongodbId];
                            self.createImageCache.count -= 1;
                            _adimageListC = _adimageList.find('input[data-mid="' + _image.mongodbId + '"]');
                            _adimageListC.prop("checked", false);
                            _adimageListTr = _adimageListC.parents("tr");
                            _adimageListTr.removeClass("active");
                        });
                        var count = self.createImageCache.count;
                        $(".image-count").text(count);
                        if (0 < count) {
                            $("#create-image-show").removeClass("disabled");
                            //有选择的图片才可以创建广告
                            $("#btn-create").removeClass("disabled");
                        } else {
                            $("#btn-create").addClass("disabled");
                            $("#create-image-show").addClass("disabled");
                        }

                        var _listArea = $("#listArea");
                        if (_listArea.find("tbody").find("input:checked").length == _listArea.find("tbody").find("tr").length) {
                            _listArea.find(".all").prop("checked", true);
                        } else {
                            _listArea.find(".all").prop("checked", false);
                        }

                    }
                    $('#create-adimage-modal').modal('hide');
                });

                //初始化复选框事件
                _createAdimageList.on('click', 'input[type="checkbox"]', function(e) {
                    if ($(e.target).hasClass("all")) {
                        if ($(e.target).get(0).checked) {
                            //全选
                            _createAdimageList.find(".create-checkbox").prop("checked", true);
                            _createAdimageList.find("tr").addClass("active");
                        } else {
                            //反选
                            _createAdimageList.find(".create-checkbox").prop("checked", false);
                            _createAdimageList.find("tr").removeClass("active");
                        }
                    } else {
                        var _createCheckbox = e.target;
                        var _tr = $(_createCheckbox).parents("tr");
                        if ($(_createCheckbox).get(0).checked) {
                            _tr.addClass("active");
                        } else {
                            _tr.removeClass("active");
                        }

                        if (_createAdimageList.find("tbody").find("input:checked").length == _createAdimageList.find("tbody").find("tr").length) {
                            _createAdimageList.find(".all").prop("checked", true);
                        } else {
                            _createAdimageList.find(".all").prop("checked", false);
                        }
                    }

                    var count = _createAdimageList.find("tbody").find("input:checked").length;
                    $('#create-adimage-modal-title').html(I18N.getText('imageManage', 'selectedImageDesc') + '(' + count + I18N.getText('imageManage', 'item') + '）');
                });
            },
            /**
             * 查看已选择的待创建的图片
             */
            showSelectImages: function(e) {
                var self = this;
                if ($(e.currentTarget).hasClass("disabled")) {
                    return false;
                }
                //$('#create-adimage-modal').dialog('option','title', '已选图片（' + self.createImageCache.count + '张）');
                //打开重新按图片选择顺序渲染列表
                var resources = [];
                //恢复排序
                $('table[list-manager="create-adimage-list"]').find(".sorting-action").removeClass("sorting-down");
                $('table[list-manager="create-adimage-list"]').find(".sorting-action").removeClass("sorting-up");

                $.each(self.createImageCache.images, function(_mongodbId, _image) {
                    resources.push(_image);
                });
                self.renderImagesList($('#select-adimage-list'), resources, self.createImageCache.images);
                var _createAdimageModal = $('#create-adimage-modal');
                _createAdimageModal.trigger('scroll'); //处理chrome 下在弹出前无法触发弹出框内的滚轴事件
                $('#create-adimage-modal-title').html(I18N.getText('imageManage', 'selectedImageDesc') + '（' + self.createImageCache.count + I18N.getText('imageManage', 'item') + '）');
                $(".show-image-container").trigger('scroll'); //处理chrome 下在弹出前无法触发弹出框内的滚轴事件


                $('#create-adimage-modal').modal({
                    backdrop: 'static',
                    keyboard: false
                });
                $('#create-adimage-modal').modal('show');
                $('#create-adimage-modal').find('td[data-operation]').remove();
                //调整表格吸顶的高度
                $('#create-adimage-modal .show-image-container').on('scroll', function() {
                    var $setTop = $('#create-adimage-modal .show-image-container .set-top');
                    if ($setTop[0]) {
                        var top = $setTop.position().top - 50;
                        $setTop.css('top', top + 'px');
                    }
                })
            },
            initCreateAdModal: function() {
                if (window.sessionStorage.roleId == 6 || window.sessionStorage.roleId == 3) {
                    return false;
                }

                var self = this;
                var par = {
                    typeId: 2 //1、主页; 2、应用
                };
                var loadingArea = $('.create-ad-select');
                self.showLoading($('.create-ad-select'));


                http.do('/connectionobjects/searchConnectionObjectsAndConfig', {
                    param: JSON.stringify(par)
                }, 'POST').then(function(data) {
                    self.hideLoading($('#listArea'));
                    if (data.flag == 'fail') {
                        kit.alert2(data.msg);
                        return;
                    }
                    data = _.sortBy(data.data, function(item) {
                        return item.name.toLowerCase();
                    });

                    var results = [{
                        id: -1,
                        text: I18N.getText('imageManage', 'plsUseAppTags')
                    }];
                    for (var i = 0; i < data.length; i++) {
                        results.push({
                            id: data[i].fbConnectionObjectId,
                            text: data[i].name,
                            configurations: data[i].productConfigurations
                        });
                    }

                    function getConfig(appId) {
                        var a = _.find(results, function(r) {
                            return r.id == appId
                        });
                        return a.configurations;
                    }

                    //初始化创建广告的应用列表
                    var _applist = $("#applist");
                    _applist.select2();
                    //_applist.html(tmpHtml);
                    _applist.select2("data", results).on("change", function(e) {
                        //切换应用重新渲染平台
                        var appid = $(this).val();
                        var configurations = [];
                        var defaultId = "-1";
                        if (-1 == appid) {
                            configurations.push({
                                id: -1,
                                text: I18N.getText('imageManage', 'plsChoosePlatform')
                            });
                        } else {
                            var infoConfigurations = getConfig(appid);
                            $.each(infoConfigurations, function(i, _configuration) {
                                configurations.push({
                                    id: _configuration.id,
                                    text: _configuration.platform
                                })
                            });
                            defaultId = infoConfigurations[0].id;
                            if (1 < configurations.length) {
                                defaultId = -1;
                                configurations.unshift({
                                    id: -1,
                                    text: I18N.getText('imageManage', 'plsChoosePlatform')
                                });
                            }
                        }

                        $("#platformlist").empty().select2({
                            data: configurations
                        }).select2("val", defaultId);
                    });
                    _applist.val('-1').trigger("change");;
                    $("#platformlist").empty().select2('data', [{
                        id: -1,
                        text: I18N.getText('imageManage', 'plsChoosePlatform')
                    }]);
                    $("#platformlist").val("-1").trigger("change");
                    self.hideLoading(loadingArea);
                }, function(msg, data, type, errorCode) {
                    self.hideLoading(loadingArea);
                    kit.alert2(I18N.getText('imageManage', 'getDatafail'));
                });


                $("#create-ad").off("click").on("click", function() {
                    var _createAdModal = $("#create-ad-modal");
                    var _app = $('#applist').val();
                    if ('-1' == _app) {
                        $("#app-area").testRemind(I18N.getText('imageManage', 'plsUseAppTags'));
                        return false;
                    }

                    var _configuration = $('#platformlist').val();
                    if ('-1' == _configuration) {
                        $("#platform-area").testRemind(I18N.getText('imageManage', 'plsChoosePlatform'));
                        return false;
                    }

                    var images = [];
                    $.each(self.createImageCache.images, function(i, _image) {
                        images.push(_image);
                    });

                    //将应用与平台存储在缓存中
                    window.localStorage.setItem('createAdAppId', _app)
                    window.localStorage.setItem('createAdPlatformId', _configuration)
                    window.localStorage.setItem('createAdImages', JSON.stringify(images))
                    $('#create-ad-modal').modal('hide');

                    //跳转到新发布页面
                    window.setTimeout(function() {
                        $('a[href="#!createAd"]').trigger('click')
                    }, 500);
                });
            },
            createByImages: function(e) {
                if ($(e.currentTarget).hasClass("disabled")) {
                    return false;
                }


                $('#create-ad-modal').modal({
                    backdrop: 'static',
                    keyboard: false
                });
                $('#create-ad-modal').modal('show');
                $('#create-ad-modal').removeAttr('tabindex');

            },
            centsToDollar: function(cents) {
                return ("$" + (Number(cents) / 100).toFixed(2));
            },

            /**
             * { 成功提醒 }
             *
             * @method     okMsg
             * @param      {<type>}  msg     { description }
             */
            okMsg: function(msg) {
                showTip({
                    time: 5, // 永不消失， 如果需要定时消失，这里写数字，30 （表示30s后自动消失）
                    type: "success",
                    bind: $("#upload-adimage-modal .modal-body"), //显示在哪里，DOM jquery对象
                    content: msg,
                    icon: "<i class='glyphicon glyphicon-flag'></i>",
                    close: false
                });
            },
            /**
             * { 错误提醒 }
             *
             * @method     errorMsg
             * @param      {<type>}  msg     { description }
             */
            errorMsg: function(msg) {
                showTip({
                    time: 5, // 永不消失， 如果需要定时消失，这里写数字，30 （表示30s后自动消失）
                    type: "error",
                    bind: $("#upload-adimage-modal .modal-body"), //显示在哪里，DOM jquery对象
                    content: msg,
                    icon: "<i class='glyphicon glyphicon-flag'></i>",
                    close: false
                });
            },

            initUploadI18n: function() {
                if (localStorage.language == 'en-us') {

                    $.fn.fileinputLocales['en-us'] = {
                        fileSingle: 'file',
                        filePlural: 'files',
                        browseLabel: 'Browse &hellip;',
                        removeLabel: 'Remove',
                        removeTitle: 'Clear selected files',
                        cancelLabel: 'Cancel',
                        cancelTitle: 'Abort ongoing upload',
                        uploadLabel: 'Upload',
                        uploadTitle: 'Upload selected files',
                        msgZoomTitle: 'View details',
                        msgZoomModalHeading: 'Detailed Preview',
                        msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
                        msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
                        msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
                        msgFileNotFound: 'File "{name}" not found!',
                        msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
                        msgFileNotReadable: 'File "{name}" is not readable.',
                        msgFilePreviewAborted: 'File preview aborted for "{name}".',
                        msgFilePreviewError: 'An error occurred while reading the file "{name}".',
                        msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
                        msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
                        msgValidationError: 'File Upload Error',
                        msgLoading: 'Loading file {index} of {files} &hellip;',
                        msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
                        msgSelected: '{n} {files} selected',
                        msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
                        msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
                        msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
                        msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
                        msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
                        dropZoneTitle: '<p class="upload-icon"><img src="./imgs/upload.png"></p><p>click & drop files here<p><button class="upload-button" type="button">upload</button></p><p>Recommend picture size 1200*628px、600*600px</p>',
                    };
                } else {

                    $.fn.fileinputLocales['zh'] = {
                        fileSingle: '文件',
                        filePlural: '个文件',
                        browseLabel: '选择 &hellip;',
                        removeLabel: '移除',
                        removeTitle: '清除选中文件',
                        cancelLabel: '取消',
                        cancelTitle: '取消进行中的上传',
                        uploadLabel: '上传',
                        uploadTitle: '上传选中文件',
                        msgZoomTitle: '查看详情',
                        msgZoomModalHeading: '详细预览',
                        isThirdPic: false,
                        msgSizeTooLarge: '文件 "{name}" (<b>{size} KB</b>) 超过了允许大小 <b>{maxSize} KB</b>.',
                        msgFilesTooLess: '你必须选择最少 <b>{n}</b> {files} 来上传. ',
                        msgFilesTooMany: '选择的上传文件个数 <b>({n})</b> 超出最大文件的限制个数 <b>{m}</b>.',
                        msgFileNotFound: '文件 "{name}" 未找到!',
                        msgFileSecured: '安全限制，为了防止读取文件 "{name}".',
                        msgFileNotReadable: '文件 "{name}" 不可读.',
                        msgFilePreviewAborted: '取消 "{name}" 的预览.',
                        msgFilePreviewError: '读取 "{name}" 时出现了一个错误.',
                        msgInvalidFileType: '不正确的类型 "{name}". 只支持 "{types}" 类型的文件.',
                        msgInvalidFileExtension: '过滤掉 "{name}". 只支持 "{extensions}" 的文件扩展名.',
                        msgValidationError: '文件错误',
                        msgLoading: '加载第 {index} 文件 共 {files} &hellip;',
                        msgProgress: '加载第 {index} 文件 共 {files} - {name} - {percent}% 完成.',
                        msgSelected: '{n} {files} 选中',
                        msgFoldersNotAllowed: '只支持拖拽文件! 跳过 {n} 拖拽的文件夹.',
                        msgImageWidthSmall: '宽度的图像文件的"{name}"的必须是至少{size}像素.',
                        msgImageHeightSmall: '图像文件的"{name}"的高度必须至少为{size}像素.',
                        msgImageWidthLarge: '宽度的图像文件"{name}"不能超过{size}像素.',
                        msgImageHeightLarge: '图像文件"{name}"的高度不能超过{size}像素.',
                        dropZoneTitle: '<p class="upload-icon"><img src="./imgs/upload.png"></p><p>图片拖放到这里</p><p>或</p><p><button class="upload-button" type="button">上传</button></p><p>普通图片:长和宽均需要在458-1200px之间,建议尺寸:1200*628;</p><p>轮播图片:长和宽必须为600*600.</p>',
                        slugCallback: function(text) {
                            return text ? text.split(/(\\|\/)/g).pop().replace(/[^\w\u4e00-\u9fa5\-.\\\/ ]+/g, '') : '';
                        },
                        fileActionSettings: {
                            removeTitle: '删除文件',
                            uploadTitle: '上传文件',
                            indicatorNewTitle: '没有上传',
                            indicatorSuccessTitle: '上传',
                            indicatorErrorTitle: '上传错误',
                            indicatorLoadingTitle: '上传 ...'
                        }
                    };
                }


            }


        });

        return new Manage();


    });
